//
//  MyOrderDetailsViewController.swift
//  Pods
//
//  Created by eme on 2017/3/31.
//
//

import UIKit
import UtilCore
import RxSwift
import RickonCore

var isrefresh_orderList = false

class MyOrderDetailsViewController: Empty_TVc,CombinedOrderProtocol {
    
    /****************************Storyboard UI设置区域****************************/
    @IBOutlet weak var CustomTableView: UITableView!                //表
    @IBOutlet weak var BottomView: UIView!                          //底部View(按钮)
    
    @IBOutlet weak var AllpriceLabel: UILabel!                      //共计Label
    @IBOutlet weak var right_Button: UIButton!                      //右边按钮
    @IBOutlet weak var left_Button: UIButton!                       //左边按钮
    
    @IBOutlet weak var tableViewWithBottom: NSLayoutConstraint!     //表距离底部距离
    
    /*----------------------------   自定义属性区域    ----------------------------*/
    var orderID:String?                                              //订单ID
    var pushType:String?                                             //跳转界面类型
    
    var OrderDetailsVm:OrderDetailsViewModel?
    
    var orderType = ""{                                              //订单类型(待付款....)
        didSet{
            self.CustomTableView.reloadData()
        }
    }
    var remainingStr = ""                                            //支付剩余倒计时
    
    var remaining:NSDateComponents! = nil                            //格式化时间
    
    var timer = Timer()                                              //定时器
    
    var countdownType = 0                                            //倒计时类型(确认收货倒计时,待付款倒计时)
    
    var DeleteVm:DeleteOrderVm?                                      //删除订单ViewModel
    
    var ConfirmVm:ConfirmOrderVm?                                    //确认收货ViewModel
    
    var ChangeOrderStatus:Change_OrderStatus?                        //修改订单状态ViewModel
    
    var orderDetails:OrderDetailsModel?{                             //数据源
        didSet{
            switch orderDetails!.orderstatus {
            case "0":
                self.orderType = "待付款"
                self.countdownType = 1
                self.setTime(data: self.orderDetails!.closeorderlefttime)
                self.createTimer()
            case "1":
                self.orderType = "待发货"
            case "2":
                self.orderType = "待发货"
            case "3":
                self.orderType = "部分发货"
            case "4":
                self.orderType = "已发货"
                self.countdownType = 2
                self.setTime(data: self.orderDetails!.receivegoodslefttime)
                self.createTimer()
            case "5":
                self.orderType = "已收货"
            case "6":
                self.orderType = "已完成"
            case "7":
                self.orderType = "已取消"
            case "8":
                self.orderType = "已驳回"
            case "9":
                self.orderType = "已关闭"
            case "10":
                self.orderType = "已过期"
            default:
                break
            }
            if self.orderType == "待付款"
            {
                self.left_Button.isHidden = true
                self.AllpriceLabel.text = "合计:\((orderDetails!.orderamount - orderDetails!.paycoupon).getPriceStr())元"
                self.right_Button.setTitle("立即付款", for: .normal)
                self.right_Button.setBackgroundImage(Theme.btn.normal.getImage(), for: .normal)
                self.right_Button.setBackgroundImage(Theme.btn.disabled.getImage(), for: .disabled)
                self.right_Button.setBackgroundImage(Theme.btn.highlighted.getImage(), for: .highlighted)
                self.right_Button.setTitleColor(UIColor.white, for: .normal)
                self.right_Button.layer.masksToBounds = true
                self.right_Button.layer.cornerRadius = 5
            }
            if self.orderType == "已关闭" || self.orderType == "已取消" || self.orderType == "已驳回" || self.orderType == "已过期"
            {
                self.left_Button.isHidden = true
                self.AllpriceLabel.isHidden = true
                self.right_Button.setBackgroundImage(UIColor.white.getImage(), for: .normal)
                self.setBottomButton(self.right_Button, title: "删除订单",titColor: UIColor(hex:"666666"),borderColor: UIColor(hex: "999999"))
            }
            if self.orderType == "待发货" || self.orderType == "待发货"
            {
                self.BottomView.isHidden = true
                self.tableViewWithBottom.constant = -49
            }
            //部分发货
            if self.orderType == "部分发货"{
                
                self.left_Button.isHidden = true
                self.AllpriceLabel.isHidden = true
                self.setBottomButton(self.right_Button, title: "查看物流",titColor: UIColor(hex:"666666"),borderColor: UIColor(hex: "999999"))
            }
            if self.orderType == "已发货"{
                self.AllpriceLabel.isHidden = true
                
                self.setBottomButton(self.left_Button, title: "查看物流",titColor: UIColor(hex:"666666"),borderColor: UIColor(hex: "999999"))
                
                self.right_Button.setTitle("确认收货", for: .normal)
                self.right_Button.setBackgroundImage(Theme.btn.normal.getImage(), for: .normal)
                self.right_Button.setBackgroundImage(Theme.btn.disabled.getImage(), for: .disabled)
                self.right_Button.setBackgroundImage(Theme.btn.highlighted.getImage(), for: .highlighted)
                self.right_Button.setTitleColor(UIColor.white, for: .normal)
                self.right_Button.layer.masksToBounds = true
                self.right_Button.layer.cornerRadius = 5
                
            }
            if self.orderType == "已收货" || self.orderType == "已完成"{
                
                self.AllpriceLabel.isHidden = true
                
                if self.orderDetails!.isevaluate == "0"{
                    self.setBottomButton(self.left_Button, title: "查看物流",titColor: UIColor(hex:"666666"),borderColor: UIColor(hex: "999999"))
                    self.right_Button.setBackgroundImage(UIColor.white.getImage(), for: .normal)
                    self.setBottomButton(self.right_Button, title: "评价",titColor: UIColor(hex:"e31436"),borderColor: UIColor(hex: "e31436"))
                }else{
                    
                    self.setBottomButton(self.right_Button, title: "查看物流",titColor: UIColor(hex:"666666"),borderColor: UIColor(hex: "999999"))
                    self.left_Button.isHidden = true
                    isrefresh_orderList = true
                }
                
            }
            self.CustomTableView.reloadData()
        }
    }

    
    var kdModel:KuaidiModel?{
        didSet{
            self.CustomTableView.reloadData()
        }
    }
    var customDate:(hour:Int,minute:Int,second:Int)?
    /****************************Storyboard 绑定方法区域****************************/
    // 打电话
    @IBAction func callPhone(_ sender: UIButton) {
        
        UIApplication.shared.openURL(URL(string :"tel://"+"\(self.orderDetails!.agmobile)")!)
//        self.showAlert("", title: orderDetails!.agmobile) { _ in
//            
//        }
        
    }
    @IBAction func bottomButtonClicked(_ sender: UIButton) {
        //根据按钮标题来判断需要进行的操作
        //查看物流,确认收货
        if sender.titleLabel?.text == "立即付款"{
            
            if orderDetails!.payarray.count > 1{
                
                self.combinedOrderEvent(vc: self, type: "fk", model: orderDetails!.payarray, payid: orderDetails!.payid)
                
            }else{
                
                _ = "pay".openURL(["orderid":"","ordersumamount":(orderDetails!.orderamount - orderDetails!.paycoupon).getPriceStr(),"payid":self.orderDetails!.payid,"ordertype":"OS"])
            }
            
        }
        if sender.titleLabel?.text == "删除订单"{
            
            self.showAlert("确认删除订单?", title: "温馨提示", handler: { _ in
                
                self.DeleteVm?.deleteOrder.onNext(self.orderDetails!.orderid)
            })
            
        }
        if sender.titleLabel?.text == "评价"{
            
            _ = "evaluation".openURL(["orderid":self.orderDetails!.orderid])
        }
        if sender.titleLabel?.text == "确认收货"{
            
            self.showAlert("是否确认收货?", title: "温馨提示", handler: { _ in
                
                self.ConfirmVm?.confirmOrderId.onNext(self.orderDetails!.orderid)
                
            })
        }
        if sender.titleLabel?.text == "查看物流"{
            _ = "logistics".openURL(["orderid":self.orderDetails!.orderid])
        }
        
        
    }
    /**
     显示提示框
     */
    func showAlert(_ message:String ,title:String ,handler: ((UIAlertAction) -> Void)?) {
        let aleatView = UIAlertController(title:title , message: message, preferredStyle:.alert)
        let archiveAction = UIAlertAction.init(title: "确定", style: .default, handler: handler)
        let cancelAction = UIAlertAction(title: "取消", style: UIAlertActionStyle.cancel, handler: nil)
        aleatView.addAction(cancelAction)
        aleatView.addAction(archiveAction)
        self.present(aleatView, animated: true, completion: nil)
    }
    
    /**************************** 以下是方法区域 ****************************/
    override func viewDidLoad() {
        super.viewDidLoad()
        
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.OrderDetailsVm!.iscanevaluate = "0"
        self.OrderDetailsVm!.getOrderDetails.onNext(self.orderID ?? "")
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        self.timer.invalidate()
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        
    }
    /**
     界面基础设置
     */
    override func setupUI() {
        /**
         *  自定义 导航栏左侧 返回按钮
         */
        self.customLeftBarButtonItem()
        self.setUpTableView()
    }
    func setUpTableView(){
        
        self.CustomTableView.showsVerticalScrollIndicator = false
        self.CustomTableView.delegate = self
        self.CustomTableView.dataSource = self
        self.CustomTableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
        self.CustomTableView.estimatedRowHeight = 100
        self.CustomTableView.rowHeight = UITableViewAutomaticDimension
        self.CustomTableView.tableHeaderView = UIView(frame: CGRect.init(x: 0, y: 0, width: 0, height: 0.1))
    }
    
    func setTime(data:Int64){
        
        self.customDate = (second: Int(data/1000 % 60),minute:Int((data/1000 / 60) % 60),hour:Int(data/1000 / 3600))
        
    }
    func createTimer(){
        self.timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector:#selector(Header_type2_TableViewCell.timeheader), userInfo: nil, repeats: true)
        self.timer.fire()
    }
    func timeheader(){
        
        if self.customDate!.hour <= 0 &&  self.customDate!.minute <= 0 && self.customDate!.second <= 0{
            
            timer.invalidate()
            self.customDate?.hour = 0
            self.customDate?.minute = 0
            self.customDate?.second = 0
            
            if self.orderType == "待付款"{
                
                self.ChangeOrderStatus?.payid = self.orderDetails!.payid
                self.ChangeOrderStatus?.changeOrderStatus_Cancel.onNext(self.orderID ?? "")
            }else{
                self.ChangeOrderStatus?.payid = self.orderDetails!.payid
                self.ChangeOrderStatus?.changeOrderStatus_Confirm.onNext(self.orderID ?? "")
            }
            
        }else{
            if self.customDate?.second == 0{
                
                if customDate?.minute == 0{
                    
                    customDate?.hour -= 1
                    customDate?.minute = 59
                    customDate?.second = 59
                    
                }else{
                    
                    customDate?.minute -= 1
                    customDate?.second = 59
                }
                
                
            }else{
                customDate?.second -= 1
            }
        }
    }
    /**
     设置按钮样式
     */
    func setBottomButton(_ button:UIButton,title:String,titColor:UIColor,borderColor:UIColor){
        button.setTitle(title, for: .normal)
        button.setTitleColor(titColor, for: .normal)
        button.layer.borderColor = borderColor.cgColor
        button.layer.borderWidth = 1
        button.layer.masksToBounds = true
        button.layer.cornerRadius = 5
    }
    /**
     查看组合商品以及投诉
     */
    func lookGroupGoods(_ button:UIButton){
        
        if button.titleLabel?.text == "点击查看"
        {
            _ = "OrderGroup".openURL(["orderid":orderDetails!.orderDetailsArray[button.tag].orderid,"pdid":"\(orderDetails!.orderDetailsArray[button.tag].pdid)"])        //跳转到查看组合商品列表
        }
        else
        {
            //投诉
            _ = "complaints".openURL(["detailid":orderDetails!.orderDetailsArray[button.tag].detailid])
        }
        
        
    }
    func to_TKVC(_ sender:UIButton){
        
        _ = "refundDetailsVc".openURL(["id":orderDetails!.orderDetailsArray[sender.tag].detailid])
    }
    /**
     绑定到viewmodel 设置
     */
    override func bindToViewModel(){
        
        
        //----------
        //获取订单详情
        self.OrderDetailsVm = OrderDetailsViewModel()
        
        self.OrderDetailsVm?.backDate.asObservable().subscribe(onNext:{ data in
            
            self.orderDetails = data
            switch data.orderstatus{
            case "0","4":
                break
            default:
                self.timer.invalidate()
            }
            
            self.OrderDetailsVm?.getOrderKD.onNext(self.orderID ?? "")
            
            }).addDisposableTo(disposeBag)
        
        
        self.OrderDetailsVm?.kdbackDate.asObserver().subscribe(onNext:{ data in
            
            self.kdModel = data
            
            }).addDisposableTo(disposeBag)
        
        self.OrderDetailsVm?.loading.asObservable().bindTo(self.view.rx_loading).addDisposableTo(disposeBag)
        
        self.OrderDetailsVm?.error.asObservable().bindTo(self.view.rx_error).addDisposableTo(disposeBag)
        
        
        //----------
        //删除订单
        
        self.DeleteVm = DeleteOrderVm()
        
        self.DeleteVm?.backDate.asObservable().subscribe(onNext:{ data in
            
            if data == true{
                isrefresh_orderList = true
                _ = self.navigationController?.popViewController(animated: true)
            }
            
            }).addDisposableTo(disposeBag)
        
        self.DeleteVm?.error.bindTo(self.view.rx_error).addDisposableTo(disposeBag)
        
        //----------
        //确认收货
        self.ConfirmVm = ConfirmOrderVm()
        
        self.ConfirmVm?.backDate.asObserver().subscribe(onNext:{ result in
            if result == true{
                
                isrefresh_orderList = true
                _ = self.navigationController?.popViewController(animated: true)
            }
            
            }).addDisposableTo(disposeBag)
        
        self.ConfirmVm?.error.bindTo(self.view.rx_error).addDisposableTo(disposeBag)
        
        //修改订单状态
        self.ChangeOrderStatus = Change_OrderStatus()
        
        self.ChangeOrderStatus?.backData.asObserver().subscribe(onNext:{ data in
            
            isrefresh_orderList = true
            if data.orderstatus != "0"{
                self.orderDetails = data
            }
            self.CustomTableView.reloadData()
            
        }).addDisposableTo(disposeBag)
        
        self.ChangeOrderStatus?.error.bindTo(self.view.rx_error).addDisposableTo(disposeBag)
    }
}
extension MyOrderDetailsViewController:UITableViewDelegate,UITableViewDataSource{
    func numberOfSections(in tableView: UITableView) -> Int {
        return 5
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if let model = self.orderDetails{
            switch section {
            case 0:
                if orderType == "已关闭" || orderType == "待审核" || orderType == "已取消" || orderType == "已驳回" || orderType == "待发货" || orderType == "已过期"{
                    
                    return 2
                    
                }else{
                    
                    return 3
                }
            case 1:
                if model.comment == ""{
                    return model.orderDetailsArray.count + 1    //由于需要显示HeaderCell所以+1
                }else{
                    return model.orderDetailsArray.count + 2   //由于需要显示HeaderCell,留言cell_所以+2
                }
                
            case 2:
                if orderDetails?.isinvoice == "1"{
                    
                    return 1
                    
                }else{
                    
                    return 0
                }
                
            case 3:
                if orderDetails?.paycoupon == 0{
                    
                    return 3
                    
                }else{
                    
                    return 4
                }
            case 4:
                switch orderType {
                case "待付款":
                    return 2
                case "已取消","待发货","待审核","已过期":
                    return 3
                case "已关闭","部分发货","已发货","已驳回":
                    return 4
                case "已收货","已完成":
                    return 5
                default:
                    return 0
                }
            default:
                return 0
            }
        }
        else
        {
            return 0
        }
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        
        switch indexPath.section {
        case 0:
            if orderType == "已关闭" || orderType == "待审核" || orderType == "已取消" || orderType == "已驳回" || orderType == "待发货" || orderType == "已过期"{
                if indexPath.row == 0{
                    let cell = tableView.dequeueReusableCell(withIdentifier: "headertype2") as! Header_type2_TableViewCell
                    cell.orderDeatils = self.orderDetails
                    cell.timeRemaining_Label.isHidden = true
                    guard #available(iOS 9.0, *) else {
                        cell.setNeedsUpdateConstraints()
                        cell.updateConstraintsIfNeeded()
                        return cell
                    }
                    return cell
                }else{
                    let consumerscell = tableView.dequeueReusableCell(withIdentifier: "consumers") as! Consumers_Message_TableViewCell
                    consumerscell.item = orderDetails
                    
                    guard #available(iOS 9.0, *) else {
                        consumerscell.setNeedsUpdateConstraints()
                        consumerscell.updateConstraintsIfNeeded()
                        return consumerscell
                    }
                    return consumerscell
                }
            }else{
                switch indexPath.row {
                case 1:
                    let cell = tableView.dequeueReusableCell(withIdentifier: "ordertype")  as! Order_Type_TableViewCell
                    cell.item = self.kdModel
                    cell.status = orderDetails!.orderstatus
                    guard #available(iOS 9.0, *) else {
                        cell.setNeedsUpdateConstraints()
                        cell.updateConstraintsIfNeeded()
                        return cell
                    }
                    return cell
                case 0:
                    if self.orderType == "待付款"{
                        let cell = tableView.dequeueReusableCell(withIdentifier: "Header_Type1") as! Header_Type1_TableViewCell
                        cell.changOrderStatus = self.ChangeOrderStatus
                        cell.orderid = self.orderID
                        cell.payid = self.orderDetails!.payid
                        cell.timer = self.timer
                        if let date = self.customDate{
                            cell.customDate = date
                        }
                        guard #available(iOS 9.0, *) else {
                            cell.setNeedsUpdateConstraints()
                            cell.updateConstraintsIfNeeded()
                            return cell
                        }
                        return cell
                    }else if self.orderType == "已发货"{
                        let cell = tableView.dequeueReusableCell(withIdentifier: "headertype2") as! Header_type2_TableViewCell
                        cell.timer = self.timer
                        cell.orderid = self.orderID
                        cell.payid = orderDetails!.payid
                        cell.changeOrderStatus = self.ChangeOrderStatus
                        cell.orderType = "已发货"
                        cell.customDate = self.customDate!
                        cell.timeRemaining_Label.isHidden = false
                        cell.orderDeatils = self.orderDetails
                        guard #available(iOS 9.0, *) else {
                            cell.setNeedsUpdateConstraints()
                            cell.updateConstraintsIfNeeded()
                            return cell
                        }
                        return cell
                    }else{
                        let cell = tableView.dequeueReusableCell(withIdentifier: "headertype2") as! Header_type2_TableViewCell
                        cell.timeRemaining_Label.isHidden = true
                        cell.orderDeatils = self.orderDetails
                        guard #available(iOS 9.0, *) else {
                            cell.setNeedsUpdateConstraints()
                            cell.updateConstraintsIfNeeded()
                            return cell
                        }
                        return cell
                    }
                default:
                    let consumerscell = tableView.dequeueReusableCell(withIdentifier: "consumers") as! Consumers_Message_TableViewCell
                    consumerscell.item = orderDetails
                    guard #available(iOS 9.0, *) else {
                        consumerscell.setNeedsUpdateConstraints()
                        consumerscell.updateConstraintsIfNeeded()
                        return consumerscell
                    }
                    return consumerscell
                }
            }
        case 1:
            let cell = tableView.dequeueReusableCell(withIdentifier: "goodsCell") as! Goods_Message_TableViewCell
            if indexPath.row > 0{
                cell.left_Button.tag = indexPath.row - 1
                cell.right_Button.tag = indexPath.row - 1
                if indexPath.row <= orderDetails!.orderDetailsArray.count{
                    
                    let model = orderDetails!.orderDetailsArray[indexPath.row - 1]
                    if orderType == "待付款" || orderType == "已取消" || orderType == "已驳回" || orderType == "已关闭" || orderType == "已完成" || orderType == "已过期"
                    {
                        if model.pdtype == "1"{
                            
                            cell.pdtypeLable.isHidden = false
                            cell.right_Button.isHidden = false
                            cell.left_Button.isHidden = true
                            cell.left_Button.setTitle("点击查看", for: .normal)
                            cell.pdtypeLable.text = "自由组合"
                            cell.lineWithBtn.constant = 10
                            
                        }else if model.pdtype == "2"{
                            
                            cell.pdtypeLable.isHidden = false
                            cell.right_Button.isHidden = false
                            cell.left_Button.isHidden = true
                            cell.left_Button.setTitle("点击查看", for: .normal)
                            cell.pdtypeLable.text = "买送组合"
                            cell.lineWithBtn.constant = 10
                            
                        }else{
                            
                            cell.pdtypeLable.isHidden = true
                            cell.right_Button.isHidden = true
                            cell.left_Button.isHidden = true
                            cell.lineWithBtn.constant = -30
                        }
                        
                    }else{
                        
                        if model.pdtype == "1"{
                            
                            cell.pdtypeLable.isHidden = false
                            cell.right_Button.isHidden = false
                            cell.left_Button.isHidden = false
                            cell.left_Button.setTitle("投诉", for: .normal)
                            cell.right_Button.setTitle("点击查看", for: .normal)
                            cell.pdtypeLable.text = "自由组合"
                            cell.lineWithBtn.constant = 10
                            
                        }else if model.pdtype == "2"{
                            
                            cell.pdtypeLable.isHidden = false
                            cell.right_Button.isHidden = false
                            cell.left_Button.isHidden = false
                            cell.left_Button.setTitle("投诉", for: .normal)
                            cell.right_Button.setTitle("点击查看", for: .normal)
                            cell.pdtypeLable.text = "买送组合"
                            cell.lineWithBtn.constant = 10
                            
                        }else{
                            
                            cell.pdtypeLable.isHidden = true
                            cell.left_Button.isHidden = true
                            cell.right_Button.isHidden = false
                            cell.right_Button.setTitle("投诉", for: .normal)
                            cell.lineWithBtn.constant = 10
                        }
                    }
                    
                    if model.detailstatus == "2"
                    {
                        cell.number_Label.text = "x \(model.detailrnumber)"
                        cell.Number_Button.setTitle("退款成功 >", for: .normal)
                        cell.Number_Button.addTarget(self, action: #selector(MyOrderDetailsViewController.to_TKVC(_:)), for: .touchUpInside)
                        cell.Number_Button.tag = indexPath.row - 1
                        cell.left_Button.isHidden = true
                        
                    }
                    else if model.detailstatus == "4"
                    {
                        cell.number_Label.text = "x \(model.detailrnumber)"
                        cell.Number_Button.setTitle("售后标记", for: .normal)
                        cell.Number_Button.isEnabled = true
                        cell.left_Button.isHidden = true
                    }
                    else
                    {
                        cell.number_Label.text = ""
                        cell.Number_Button.setTitle("x \(model.detailrnumber)", for: .normal)
                    }
                    if model.detailstatus == "2" || model.detailstatus == "4"{
                        if  model.pdtype != "1" && model.pdtype != "2"{
                            cell.left_Button.isHidden = true
                            cell.right_Button.isHidden = true
                            cell.lineWithBtn.constant = -30
                        }
                    }
                    
                    cell.goods_NameLabel.text = model.pdname
                    cell.priceLabel.text = model.shprice.getPriceStr()
                    
                    if model.pdtype == "0"{
                        
                        cell.standard_Label.text = model.standard
                        
                    }else{
                        
                        cell.standard_Label.text = ""
                    }
                    
                    
                    cell.goods_ImageView.setUrlImage(model.img1)
                }
            }
            cell.left_Button.addTarget(self, action: #selector(MyOrderDetailsViewController.lookGroupGoods(_:)), for: .touchUpInside)
            cell.right_Button.addTarget(self, action: #selector(MyOrderDetailsViewController.lookGroupGoods(_:)), for: .touchUpInside)
            //顶部Cell(品牌商,服务商)
            let Headercell = tableView.dequeueReusableCell(withIdentifier: "storeHeader") as! Store_Header_TableViewCell
            Headercell.storeName_Label.text = orderDetails!.agname
            Headercell.PName_Label.text = orderDetails!.bdname
            //留言Cell
            let leaveWordcell = tableView.dequeueReusableCell(withIdentifier: "leaveWord") as! Leave_Word_TableViewCell
            leaveWordcell.item = orderDetails!.comment
            switch indexPath.row {
            case 0:
                guard #available(iOS 9.0, *) else {
                    Headercell.setNeedsUpdateConstraints()
                    Headercell.updateConstraintsIfNeeded()
                    return Headercell
                }
                return Headercell
            case orderDetails!.orderDetailsArray.count + 1:
                guard #available(iOS 9.0, *) else {
                    leaveWordcell.setNeedsUpdateConstraints()
                    leaveWordcell.updateConstraintsIfNeeded()
                    return leaveWordcell
                }
                return leaveWordcell
            default:
                guard #available(iOS 9.0, *) else {
                    cell.setNeedsUpdateConstraints()
                    cell.updateConstraintsIfNeeded()
                    return cell
                }
                return cell
            }
        case 3:
            let cell = tableView.dequeueReusableCell(withIdentifier: "other") as! OtherTableViewCell
            let f1cell = tableView.dequeueReusableCell(withIdentifier: "F1Cell") as! F1CellTableViewCell
            let payFootcell = tableView.dequeueReusableCell(withIdentifier: "payFoot") as! Pay_Foot_TableViewCell
            payFootcell.contentView.backgroundColor = UIColor.white
            payFootcell.payLabel.text = (orderDetails!.orderamount - orderDetails!.paycoupon).getPriceStr()
            if orderDetails!.paycoupon != 0{
                if indexPath.row == 2{
                    
                    cell.right_Label.textColor = UIColor(hex: "e31436")
                }else{
                    cell.right_Label.textColor = UIColor(hex: "333333")
                }
                cell.left_Label.text = ["商品金额","优惠券","共计",""][indexPath.row]
                //-----------
                cell.right_Label.text = ["共\(orderDetails!.totalnumber)件,\(orderDetails!.orderamount.getPriceStr())","- \(orderDetails!.paycoupon.getPriceStr())","\((orderDetails!.orderamount - orderDetails!.paycoupon).getPriceStr())",""][indexPath.row]
                //===========
                if orderType == "待付款" || orderType == "已取消" || orderType == "已过期"{
                    if indexPath.row == 3{
                        
                        return f1cell
                        
                    }else{
                        
                        return cell
                    }
                    
                }else{
                    
                    if indexPath.row == 3{
                        
                        return payFootcell
                    }else{
                        return cell
                    }
                }
            }else{
                if indexPath.row == 1{
                    
                    cell.right_Label.textColor = UIColor(hex: "e31436")
                }else{
                    cell.right_Label.textColor = UIColor(hex: "333333")
                }
                cell.left_Label.text = ["商品金额","共计",""][indexPath.row]
                
                cell.right_Label.text = ["共\(orderDetails!.totalnumber)件,\(orderDetails!.orderamount.getPriceStr())","\((orderDetails!.orderamount - orderDetails!.paycoupon).getPriceStr())",""][indexPath.row]
                
                if orderType == "待付款" || orderType == "已取消" || orderType == "已过期"{
                    if indexPath.row == 2{
                        
                        return f1cell
                        
                    }else{
                        return cell
                    }
                    
                }else{
                    
                    if indexPath.row == 2{
                        
                        return payFootcell
                    }else{
                        return cell
                    }
                }
            }
        default:
            let cell = tableView.dequeueReusableCell(withIdentifier: "other") as! OtherTableViewCell
            
            switch indexPath.section {
            case 2:
                cell.left_Label.text = "发票抬头"
                cell.right_Label.text = orderDetails!.invoicetitle
                
            case 4:
                
                if orderType == "已关闭"  || orderType == "已驳回"
                {
                    
                    cell.left_Label.text = ["订单编号","下单时间","付款时间","取消时间"][indexPath.row]
                    cell.right_Label.text = [orderDetails!.orderid,orderDetails!.underdate,orderDetails!.paydate,orderDetails!.canceltime][indexPath.row]
                }
                else if orderType == "已取消"
                {
                    
                    cell.left_Label.text = ["订单编号","下单时间","取消时间"][indexPath.row]
                    cell.right_Label.text = [orderDetails!.orderid,orderDetails!.underdate,orderDetails!.canceltime][indexPath.row]
                    
                }else if orderType == "已过期"{
                    
                    cell.left_Label.text = ["订单编号","下单时间","取消时间"][indexPath.row]
                    cell.right_Label.text = [orderDetails!.orderid,orderDetails!.underdate,orderDetails!.closeorderdate][indexPath.row]
                }else{
                    cell.left_Label.text = ["订单编号","下单时间","付款时间","发货时间","收货时间"][indexPath.row]
                    cell.right_Label.text = [orderDetails!.orderid,orderDetails!.underdate,orderDetails!.paydate,orderDetails!.sendtime,orderDetails!.taketime][indexPath.row]
                }
            default:
                break
            }
            guard #available(iOS 9.0, *) else {
                cell.setNeedsUpdateConstraints()
                cell.updateConstraintsIfNeeded()
                return cell
            }
            return cell
        }
    }
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        
        if let model = orderDetails{
            switch section {
            case 1:
                let cell = tableView.dequeueReusableCell(withIdentifier: "storeHeader") as! Store_Header_TableViewCell
                cell.storeName_Label.text = model.bdname
                cell.PName_Label.text = model.agname
                guard #available(iOS 9.0, *) else {
                    cell.setNeedsUpdateConstraints()
                    cell.updateConstraintsIfNeeded()
                    return cell.contentView
                }
                return cell.contentView
            default:
                return nil
            }
        }else{
            return nil
        }
    }
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        switch section {
        case 0:
            if orderType == "待付款"{
                return 0.01
            }else{
                return 0.01
            }
        case 1:
            return 0
        default:
            return 0
        }
        
    }
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
        if orderType == "部分发货" || orderType == "已发货" || orderType == "已收货" || orderType == "已完成"{
            if indexPath.section == 0 && indexPath.row == 1{
                
                _ = "logistics".openURL(["orderid":self.orderDetails!.orderid])
            }
        }
        if indexPath.section == 1{
            
            if indexPath.row != 0{
                _ = "productdetail".openURL(["pdid":"\(self.orderDetails!.orderDetailsArray[indexPath.row - 1].pdid)"])
            }
        }
    }
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        switch section {
        case 0:
            return 7.5
        case 1:
            return 7
        case 2:
            return 0.5
        case 3:
            return 7.5
        default:
            return 7.5
        }
    }
}
